import peewee_async
from base import BaseHandler # 帖子模块
from db import Talk_Model,Sub_Talk_Model,Sub_Model,User_Model  # 导入用户模型类
from tornado.web import  url  # 导入torando路由
from utils import create_code,EmailTool,MyJwt,MyFile,jwt_token,WriteFile,Upyun,Page,acl_auth,rbac_auth
from werkzeug.security import check_password_hash,generate_password_hash
from PIL import ImageDraw,Image,ImageFont # 绘制图片   图片  字体
import re # 正则
import hashlib # 加密
import io
import random
import time
import requests
from db import database
import json
import os
import re
from functools import wraps
from abc import ABCMeta,abstractmethod
from playhouse.shortcuts import model_to_dict     # 序列化

class SubTool:
    def __init__(self):
        self.database = peewee_async.Manager(database)
    @staticmethod     # 更换头像
    def change_avtar(sublist,url):
        for x in sublist:
            if 'http' not in x['user']['avtar']:
                x['user']['avtar'] = url + x['user']['avtar'][1:]
        return sublist

    async def change_object(self,sublist,stype):
                            # 话题的正则       # 话题的模型类      # 话题的条件语句                       # 话题字典的key   # 话题的替换前的字符    # 替换后的字符
        re_dict = {'talk':{'re':r'#([\w]+)#','model':Talk_Model,'column':'Talk_Model.name.in_(items)','getkey':'q.name','replace':"#{}#",'a':"<a href='/talk?tid={}'>#{}#</a>"},
                            # 用户的正则       # 用户的模型类      # 用户的条件语句                       # 用户字典的key   # 用户的替换前的字符    # 替换后的字符
                   'at':{'re':r'@([\S]+)_','model':User_Model,'column':'User_Model.email.in_(items)','getkey':'q.email','replace':"@{}_",'a':"<a href='/userinfo?uid={}'>@{}_</a>"}}
        myre = re_dict[stype]['re']

        for x in sublist:
            items_dict = {}
            items = re.findall(myre, x['content'])
            if items:
                uids = await self.database.execute(re_dict[stype]['model'].select().where(eval(re_dict[stype]['column'])))
                for q in uids:
                    items_dict[eval(re_dict[stype]['getkey'])] = q.id
                for i in items:
                    try:
                        x['content'] = x['content'].replace(re_dict[stype]['replace'].format(i),
                                                        re_dict[stype]['a'].format(items_dict[i],i))
                    except Exception as e:
                        print(e)
                        pass

        return sublist


    # async def sublist(self,subs):
    #     sublist = [model_to_dict(x) for x in subs]
    #     for x in sublist:
    #         user_dict = {}
    #         emails = re.findall(r'@([\S]+)_', x['content'])
    #         if emails:
    #             uids = await self.application.objects.execute(User_Model.select().where(User_Model.email.in_(emails)))
    #             for q in uids:
    #                 user_dict[q.email] = q.id
    #             print(user_dict)
    #             for email in emails:
    #                 x['content'] = x['content'].replace(f"@{email}_", f"<a href='/userinfo?uid={user_dict[email]}'>@{email}_</a>")
    #         talk_dict = {}
    #         talks = re.findall(r'#([\w]+)#', x['content'])
    #         if talks:
    #             tids = await self.application.objects.execute(Talk_Model.select().where(Talk_Model.name.in_(talks)))
    #             for i in tids:
    #                 talk_dict[i.name] = i.id
    #             for talk in talks:
    #                 x['content'] = x['content'].replace(f"#{talk}#", f"<a href='/talk?tid={talk_dict[talk]}'>#{talk}#</a>")
    #         if 'http' not in x['user']['avtar']:
    #             x['user']['avtar'] = self.get_url + x['user']['avtar'][1:]
    #     return sublist

class SubHanler(BaseHandler):
    @property
    def get_url(self):
        return 'http://localhost:8000'
    @jwt_token
    async def get(self):   # 展示
        subs = await self.application.objects.execute(Sub_Model.select().order_by(-Sub_Model.id))  # 倒序
        sublist = [model_to_dict(i) for i in subs]
        sublist = SubTool.change_avtar(sublist,self.get_url)
        sublist = await SubTool().change_object(sublist,'at')
        sublist = await SubTool().change_object(sublist, 'talk')
        # sub = [model_to_dict(x) for x in subs]
        # for x in sub:
        #     talk_dict = {}
        #     talks = re.findall(r'#([\w]+)#',x['content'])
        #
        #     tids = await self.application.objects.execute(Talk_Model.select().where(Talk_Model.name.in_(talks)))
        #     for i in tids:
        #         talk_dict[i.name]=i.id
        #         print(talk_dict,'***')
        #     for talk in talks:
        #         x['content'] = x['content'].replace(f"#{talk}#",f"<a href='/talk?tid={talk_dict[talk]}'>#{talk}#</a>")
        #     if 'http' not in x['user']['avtar']:
        #         x['user']['avtar'] = self.get_url + x['user']['avtar'][1:]
        return self.finish({'errcode':0,'data':sublist})

    @jwt_token
    async def post(self):
        content = self.get_argument('content',None)
        state = self.get_argument('state','0')

        # 匹配话题
        talks = re.findall(r'#(\w+)#',content)
        sub = await self.application.objects.create(Sub_Model, content=content, state=int(state),user=self._cuser.id)
        if not talks:
            await self.application.objects.create(Sub_Talk_Model, sid=sub.id)
        else:
            for i in talks:
                try:
                    talk = await self.application.objects.create(Talk_Model,name=i)
                except Exception as e:
                    talk = await self.application.objects.get(Talk_Model,name=i)
                await self.application.objects.create(Sub_Talk_Model, sid=sub.id, tid=talk.id)
        return self.finish({'errcode':0,'msg':'发帖成功'})



class TalkHanler(BaseHandler):
    @property
    def get_url(self):
        return 'http://localhost:8000'


    async def get(self):
        tid = self.get_argument('tid',None)

        subtalk = await self.application.objects.execute(Sub_Talk_Model.select().where(Sub_Talk_Model.tid==tid))
        if not subtalk:
            return self.finish({'errcode': 1, 'msg': '该话题没有帖子'})
        sub_id = [i.sid for i in subtalk]
        subs = await self.application.objects.execute(Sub_Model.select().where(Sub_Model.id.in_(sub_id)).order_by(-Sub_Model.id))
        sublist = [model_to_dict(i) for i in subs]
        sublist = SubTool.change_avtar(sublist, self.get_url)
        sublist = await SubTool().change_object(sublist, 'at')
        sublist = await SubTool().change_object(sublist, 'talk')
        return self.finish({'errcode': 0, 'msg': '获取此话题帖子成功','data':sublist})


urlpatterns = [
    url('/sub/',SubHanler),
    url('/talk/',TalkHanler)
]













